<?php

namespace app\controllers\supplier;
use app\models\AdminSupplier as Model;
use app\redis\Cache;
use app\util\JWT;
use Yii;

/**
 * Class AdminController
 * @package app\controllers\admin
 */
class AdminController extends \app\controllers\supplier\base\AdminController
{
    /**
     * Administrator login
     *
     * @return \yii\web\Response
     */
    public function actionLogin()
    {
        $username = $this->post('username');
        $password = $this->post('password');

        if (!$username || !$password) {
            return $this->fail('请输入正确的用户名或者密码');
        }

        // php -r "echo md5('123456'. 'supplier-salt');"

        $password = md5($password . Yii::$app->params['SUPPLIER_SALT']);

        $admin = Model::login($username, $password);
        if ($admin) {

            if ($admin->status == 0) {
                return $this->fail('该帐户还没有被审核或者已经禁用');
            }

            // $admin->update_time = date('Y-m-d H:i:s');
            // $admin->save();

            $token = JWT::createToken(
                [ 'username' => $username, 'id' => $admin->id ],
                Yii::$app->params['JWT_SUPPLIER_KEY'],
                Yii::$app->params['JWT_SUPPLIER_EXPIRED']
            );

            return $this->success(['token' => $token], '登录成功');
        }

        return $this->fail('登录失败,请检查用户名或者密码是否正确');
    }

    /**
     * Get administrator info
     *
     * @return \yii\web\Response
     */
    public function actionGetInfo()
    {
        $user = Model::getInfo($this->user->username);

        if ($user !== false) {
            return $this->success($user);
        }

        return $this->fail('获取用户信息失败');
    }

    public function actionPassword()
    {
        $password_old = $this->post('password_old');
        $password = $this->post('password');
        $password2 = $this->post('password2');

        if ($password != $password2) {
            return $this->fail('两次密码不一致');
        }

        if (strlen($password) < 6) {
            return $this->fail('密码长度不能小于6位');
        }

        $password_old = md5($password_old . Yii::$app->params['SUPPLIER_SALT']);
        $model = Model::findOne(['username' => $this->user->username, 'password' => $password_old]);
        if ($model) {
            $password = md5($password . Yii::$app->params['SUPPLIER_SALT']);
            $model->password = $password;
            if ($model->save()) {
                return $this->success();
            }
        } else {
            return $this->fail('旧密码错误');
        }
    }

    /**
     * Flush all redis
     *
     * @return \yii\web\Response
     */
    public function actionClear()
    {
        if (Cache::flushAll()) {
            return $this->success();
        }

        return $this->fail();
    }
}